package com.hys.app.framework.ws.impl;


import com.alibaba.druid.util.StringUtils;
import com.hys.app.framework.ErpConfig;
import com.hys.app.framework.auth.TokenParseException;
import com.hys.app.framework.auth.TokenParser;
import com.hys.app.framework.auth.impl.JwtTokenParser;
import com.hys.app.framework.security.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * Websocket的拦截器，主要实现token的验证以及获取token对应的userid
 * Author: Dawei
 * Datetime: 2022-07-18 14:54
 */
@Component
public class WebSocketInterceptor implements HandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ErpConfig erpConfig;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverHttpRequest = (ServletServerHttpRequest) request;
            String token = serverHttpRequest.getServletRequest().getParameter("token");

            logger.debug("token is {}",token);
            String appType = serverHttpRequest.getServletRequest().getParameter("appType");

            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(appType) ) {
                logger.error("token or app type is empty");
                return false;
            }

            // 验证token
            Long userId = this.parseToken(token);

            //0说明token验证失败
            if (userId == 0) {
                return false;
            }
            //验证通过，将token对应用userid放入attribute
            attributes.put("userId",userId);
            attributes.put("appType", appType);
            return true;
        }
        return true;
    }

    /**
     * 解析token
     * @param token
     * @return 用户id
     */
    private Long parseToken(String token) {

        try {
            TokenParser tokenParser = new JwtTokenParser(erpConfig.getTokenSecret());
            User user = tokenParser.parse(User.class, token);
            return user.getUid();
        } catch (TokenParseException e) {
            logger.error("token解析失败",e);
        }

        return 0L;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
